import json
import os
import sys
from pathlib import Path

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.append(str(project_root))

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
from app.models.question import Question
from app.db.database import Base

# 数据库连接
engine = create_engine(settings.DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 确保数据库表存在
Base.metadata.create_all(bind=engine)

def convert_json_to_db_format(json_data, subject, model):
    """将 JSON 数据转换为数据库格式"""
    return {
        "subject": subject,  # k1 或 k4
        "model": model,     # 车型代码 (c1, c2 等)
        "question_type": "theory",  # 默认为理论考试题目
        "content": json_data["question"],
        "options": [
            json_data["item1"],
            json_data["item2"],
            json_data["item3"],
            json_data["item4"]
        ],
        "answer": json_data["answer"],
        "explanation": json_data["explains"],
        "image_url": json_data["url"] if json_data.get("url") else None
    }

def import_questions():
    """导入所有题目"""
    base_path = Path(__file__).parent.parent / "驾照题库"
    
    # 处理科目一
    subject1_path = base_path / "科目1"
    if subject1_path.exists():
        for json_file in subject1_path.glob("*.json"):
            model = json_file.stem.lower()  # 获取文件名作为车型代码
            print(f"正在导入科目一 {model} 的题目...")
            
            try:
                with open(json_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    questions = data.get("result", [])
                    
                    db = SessionLocal()
                    try:
                        for q in questions:
                            db_question = Question(**convert_json_to_db_format(q, "k1", model))
                            db.add(db_question)
                        db.commit()
                        print(f"成功导入 {len(questions)} 道题目")
                    except Exception as e:
                        print(f"导入出错: {str(e)}")
                        db.rollback()
                    finally:
                        db.close()
            except Exception as e:
                print(f"读取文件 {json_file} 出错: {str(e)}")
    
    # 处理科目四
    subject4_path = base_path / "科目四"
    if subject4_path.exists():
        for json_file in subject4_path.glob("*.json"):
            model = json_file.stem.lower()
            print(f"正在导入科目四 {model} 的题目...")
            
            try:
                with open(json_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    questions = data.get("result", [])
                    
                    db = SessionLocal()
                    try:
                        for q in questions:
                            db_question = Question(**convert_json_to_db_format(q, "k4", model))
                            db.add(db_question)
                        db.commit()
                        print(f"成功导入 {len(questions)} 道题目")
                    except Exception as e:
                        print(f"导入出错: {str(e)}")
                        db.rollback()
                    finally:
                        db.close()
            except Exception as e:
                print(f"读取文件 {json_file} 出错: {str(e)}")

if __name__ == "__main__":
    print("开始导入题库...")
    import_questions()
    print("导入完成！") 